//
//  IMGroupCreateController.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/7/14.
//
//  创建群聊
import UIKit
import Reusable
import JFPopup

class IMGroupCreateController: BaseViewController {
    
    @IBOutlet weak var markView: UIView!
    @IBOutlet weak var nameTitleLabel: UILabel!
    @IBOutlet weak var nameTextField: UITextField!
    
    @IBOutlet weak var memberTitleLabel: UILabel!
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    @IBOutlet weak var submitButton: UIButton!
    
    var list: [UserModel] = []
    
    let addMemberModel = UserModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNav()
        setupUI()
        updateLanguageAction()
        
        NotificationCenter.default.addObserver(self, selector: #selector(textFieldTextDidChangeNotification), name: UITextField.textDidChangeNotification, object: nameTextField)
        
    }
    
    @IBAction func addMemberAction(_ sender: Any) {
        view.endEditing(true)
        let addView = IMGroupCreateAddMemberView.loadFromNib()
        addView.closeHandler = {
            self.popup.dismissPopup()
        }
        addView.didSelectedHandler = { [self] model in
            if list.filter({ $0.id == model.id }).count > 0 {
                YLHUD.showMessage("已经添加了该成员".localized(.call))
                return
            }
            popup.dismissPopup()
            list.append(model)
            collectionView.reloadData()
        }
        popup.bottomSheet {
            addView
        }
    }
    
    @IBAction func submitAction(_ sender: Any) {
        
        if nameTextField.text!.isEmpty {
            YLHUD.showMessage("请输入群昵称".localized(.call))
            return
        }
        
        if list.isEmpty {
            YLHUD.showMessage("请添加群成员".localized(.call))
            return
        }
        
        var ids = list.map { String($0.id) }
        ids.append(String(UserProfile.userId))
        xLog("ids: \(ids.joined(separator: ","))")
        
        ZIMKit.createGroup(with: nameTextField.text!, inviteUserIDs: ids) { groupInfo, inviteUserErrors, error in
            xLog("groupInfo \(groupInfo.id) \(groupInfo.name)")
            self.back()
        }
    }
    
    override func updateLanguageAction() {
        navigationItem.title = "创建群聊".localized(.call)
        nameTextField.placeholder = "请输入".localized(.call)
        nameTitleLabel.attributedText = requiredText("群昵称")
        memberTitleLabel.attributedText = requiredText("群成员")
        submitButton.setTitle("完成".localized(.call), for: .normal)
    }
    
    func requiredText(_ content: String) -> NSAttributedString {
        let titleString = content.localized(.call) + "*"
        let text = NSMutableAttributedString(string: titleString)
        text.font(.systemFont(ofSize: 14, weight: .semibold))
        text.color(UIColor(hex: "333333"))
        if titleString.hasSuffix("*") {
            text.color(UIColor(hex: "FF0000"), range: titleString.inRange(of: "*").first!)
        }
        return text
    }
    
}

extension IMGroupCreateController {
    func setupNav() {
        // vhl_navBarBackgroundAlpha = 0
        // vhl_navBarBackgroundColor = .clear
        navigationItem.title = "创建群聊".localized(.call)
    }
    
    func setupUI() {
        submitButton.addRoundedCorners(radius: 24)
        
        markView.backgroundColor = UIColor(hex: "#FFFFFF", 0.7)
        // 设置阴影颜色
        markView.layer.shadowColor = UIColor(hex: "#9AD0FF", 0.6).cgColor
        // 设置透明度
        markView.layer.shadowOpacity = 20
        // 设置阴影半径
        markView.layer.shadowRadius = 20
        // 设置阴影偏移量
        markView.layer.shadowOffset = CGSize(width: 0, height: 4)
        
        markView.layer.cornerRadius = 20
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = 10
        layout.minimumLineSpacing = 10
        layout.scrollDirection = .vertical
        
        collectionView.setCollectionViewLayout(layout, animated: true)
        collectionView.delegate = self
        collectionView.dataSource = self
        
        collectionView.isScrollEnabled = false
        collectionView.bounces = false
        collectionView.backgroundColor = .clear
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        collectionView.register(cellType: IMGroupCreateMemberCell.self)
    }
    
    
    @objc func textFieldTextDidChangeNotification(noti: Notification) {
        let textField = noti.object as! UITextField
        
        if textField.markedTextRange != nil {
            return
        }
        
        if textField.text!.count > 12 {
            textField.text = String(textField.text!.prefix(12))
        }
       
    }
}


extension IMGroupCreateController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        list.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(for: indexPath, cellType: IMGroupCreateMemberCell.self)
        cell.model = list[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        CGSize(width: 50, height: 50)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        list.remove(at: indexPath.row)
        collectionView.reloadData()
    }
}
